package com.system.controller;


import com.system.domain.Admin;
import com.system.domain.Phones;
import com.system.domain.User;
import com.system.service.AdminLogin;
import com.system.service.Impl.AdminLoginImpl;
import com.system.service.Impl.PhoneServiceImpl;
import com.system.service.ShiroService;
import com.system.utils.CodeUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class loginController {
    @Resource
    private ShiroService shiroService;
    @Resource
    private PhoneServiceImpl phoneServiceImpl;
    @Resource
    private AdminLogin adminLogin;
    private Logger logger = Logger.getLogger(loginController.class);


    //跳到主页
    @RequestMapping("/toIndex")
    public String toIndex() {
        return "index";
    }

    @RequestMapping("/toAdmin")
    public String toAdmin() {
        return "adminlogin";
    }

    @RequestMapping("/toGuanli")
    public String toGuanli() {
        return "guanli1";
    }

    //@ResponseBody
    @RequestMapping("/user")
    public String userget(HttpSession session, HttpServletRequest request, Model model) {
        System.out.println("123454");
        //return shiroService.getUser();
        session.setAttribute("cehi1", "ceshi");
        model.addAttribute("ceshi", "1");
        //User user = shiroService.getUser();
        //System.out.println(user);
        List<User> users = shiroService.getUser();
        model.addAttribute("users", users);
        System.out.println(users);
        return "guanli1";
    }

    @RequestMapping("/xiugai")
    public String xiugai(Admin admin, Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        model.addAttribute("id", id);
        model.addAttribute("account", account);
        model.addAttribute("password", password);
        return "xiugai";
    }

    @RequestMapping("/delete")
    public String delete(HttpServletRequest request) {
        String id = request.getParameter("id");
        shiroService.delete(id);
        return "xiugaisuccess";
    }

    @RequestMapping("/updata")
    public String updata(HttpServletRequest request, Model model, User user) {
        System.out.println(user);
        int a = shiroService.updata(user);
        System.out.println(a);
        return "xiugaisuccess";

    }


    @RequestMapping("/toAdminIndex")
    public String toAdminIndex(Admin admin, Model model) {
        if (admin.getUsername() == null) {
            model.addAttribute("message", "账号不为空");
            return "adminlogin";
        }
        System.out.println(admin);
        String username = admin.getUsername();
        String password = admin.getPassword();
        Admin admin1 = adminLogin.select(username, password);

        //return "adminlogin";

        if (admin1.getUsername().equals(username) && admin1.getPassword().equals(password)) {
            List<User> users = shiroService.getUser();
            model.addAttribute("users", users);
            return "guanli1";
        } else {
            model.addAttribute("error", "账户或者密码错误");
            return "adminlogin";
        }

    }

    //跳到登录页面
//    @RequestMapping("/toLogin")
//    public String toLogin(){
//        return "login";
//    }

    //跳到注册页面
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    //跳到购物车
    @RequestMapping("/toCart_list")
    public String toCart_list() {
        return "redirect:selectCart";
    }

    //跳到商品展示页面
    @RequestMapping("/toShop_list")
    public String toShop_list(Model model) {
        List<Phones> phonesInfo = phoneServiceImpl.selectPhones();
        model.addAttribute("phonesInfo", phonesInfo);
        return "shop_list";
    }


    //跳到热卖商品页面
//    @RequestMapping("/toShop_hot")
//    public String toShop_hot(){
//        return "shop_hot";
//    }

    //注册的方法
    @RequestMapping("/getRegister")
    public String getRegister(User user) {
        System.out.println("getRegister方法进来了吗???");
        int i = shiroService.addUser(user);
        if (i > 0) {
            System.out.println("注册成功");
        } else {
            System.out.println("注册失败");
        }
        return "registerSuccess";
    }

    /**
     * 验证登录
     *
     * @param username
     * @param password
     * @param session
     * @return url
     */
    @RequestMapping(value = "/toLogin")
    public String Login(String username, String password, HttpSession session, HttpServletRequest request, Model model) {

        if (username == null) {
            model.addAttribute("message", "账号不为空");
            return "login";
        }

        /*
        这里的CodeUtil和checkVerifyCode都是调用工具类里面的内容
         */

        if (!CodeUtil.checkVerifyCode(request)) {
            System.out.println("验证码错误");
            String error = "验证码错误";
            model.addAttribute("error", error);
            return "login";
        } else {
            System.out.println("验证码正确");
        }


        //主体,当前状态为没有认证的状态“未认证”
        Subject subject = SecurityUtils.getSubject();
        // 登录后存放进shiro token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println("这是token:" + token);
        User user = null;
        //登录方法（认证是否通过）
        //使用subject调用securityManager,安全管理器调用Realm
        try {
            //利用异常操作
            //需要开始调用到Realm中
            System.out.println("========================================");
            System.out.println("1、进入认证方法");
            subject.login(token);
            user = (User) subject.getPrincipal();
            System.out.println("user:" + user);
            //通过user传递姓名
            session.setAttribute("user", subject);
            session.setAttribute("users", user);
            model.addAttribute("user", user.getAccount());
            model.addAttribute("message", "登录完成");
            System.out.println("登录完成");
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "账号或者密码不正确");
            return "LoginFailed";
        }
        return "index";
    }

    @RequestMapping("/check")
    public String check(HttpSession session) {
        Subject subject = (Subject) session.getAttribute("user");
        User user = (User) subject.getPrincipal();
        System.out.println(user.toString());
        return "permission";
    }

    //管理员进入的界面
    @RequestMapping("/readName")
    public String readName(Admin admin,HttpSession session,Model model) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        Admin admin1 = adminLogin.select(username, password);
        List<User> users = shiroService.getUser();
        model.addAttribute("users", users);
        return "guanli1";
    }

    //进入修改页面
    @RequestMapping("/toUserUpdate")
    public String toUserUpdate(){
        return "UserUpdate";
    }

    //用户进入的界面
    @RequestMapping("/readData")
    public String readData() {
        return "data";
    }

    //点击修改后,跳到修改页面
    @RequestMapping("/toUpdatePassword")
    public String UpdatePassword(int id,Model model){
        User userInfo = phoneServiceImpl.queryUserById(id);
        model.addAttribute("userInfo",userInfo);
        return "UpdatePassword";
    }

    //调用修改的方法
    @RequestMapping("/UpdateUser")
    public String UpdateUser(User user){
        System.out.println("UpdateUser.........");
        int i = phoneServiceImpl.UpdateUser(user);
        if(i>0){
            System.out.println("修改成功");
        }
        return "index";
    }


    //根据手机名字查询手机功能
    @RequestMapping("/selectPhoneByName")
    public String selectPhoneByName(String name,Model model){
        List<Phones> phones = phoneServiceImpl.selectPhoneByName(name);
        List<Phones> list = new ArrayList<Phones>();
        for (Phones phone : phones) {
            list.add(phone);
            model.addAttribute("phones",list);
        }
        return "shop_hot";
    }



    //没有登录的情况下
    @RequestMapping("/nopermission")
    public String noPermission() {
        return "error";
    }
}
